package com.googlecode.perfectable.visuable.structure;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.List;

import javax.annotation.Nullable;

import org.w3c.dom.Attr;
import org.w3c.dom.NamedNodeMap;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.googlecode.perfectable.visuable.renderer.ElementRenderer;

public class Attribute {
	private static final List<Attribute> EMPTY_ATTRIBUTE_LIST = ImmutableList.of();

	private final String name;
	private final String value;

	private Attribute(String name, String value) {
		this.name = name;
		this.value = value;
	}

	public static Attribute create(String name, String value) {
		return new Attribute(name, value);
	}

	public static Optional<String> find(Iterable<Attribute> attributes, String name) {
		for(Attribute candidate : attributes) {
			if(candidate.name.equals(name)) {
				return Optional.of(candidate.value);
			}
		}
		return Optional.absent();
	}

	public static List<Attribute> convert(@Nullable NamedNodeMap attributes) {
		if(attributes == null) {
			return empty();
		}
		final int length = attributes.getLength();
		List<Attribute> result = Lists.newLinkedList();
		for(int i = 0; i < length; i++) {
			Attr raw = (Attr) attributes.item(i);
			checkNotNull(raw);
			Attribute attribute = Attribute.create(raw.getName(), raw.getValue());
			result.add(attribute);
		}
		return result;
	}

	public static List<Attribute> empty() {
		return EMPTY_ATTRIBUTE_LIST;
	}

	public void render(ElementRenderer painter) {
		painter.attribute(this.name, this.value);
	}

	public String value() { // MARK getter
		return this.value;
	}
}
